<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/12/22
 * Time: 15:10
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\pur;

use app\admin\controller\BaseController;
use app\common\model\ChannelExpress;
use app\common\model\Producer;
use app\common\model\Purchase;
use app\common\model\PurchaseTrack;
use app\common\model\Warehouse;
use app\common\service\BaseService;
use app\common\service\purchase\PurchaseService;

/**
 * 追踪号
 * Class TrackController
 * @package app\admin\controller\pur
 */
class TrackController extends BaseController
{

    /**
     * 追踪号首页
     * @date 2021/01/18
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $track = PurchaseTrack::with([
                'purchase.warehouse',
                'purchase.producer',
                'info'
            ])->order("is_recv, track_id desc");
            $this->search($track);
            $limit = $this->getPageSize();
            $track = $track->paginate($limit);
            $this->assign('track_status_none', ChannelExpress::TRACK_STATUS_NONE);
            $this->assign("list", $track->getCollection());
            $this->assign("page", $track->render());
            return $this->fetch("lists");
        }
        $this->assign("order_status", Purchase::$ORDER_STATUS);
        $this->assign("track_status", ChannelExpress::$TRACK_STATUS);
        $this->assign("producer", Producer::getAll());
        $this->assign("warehouse", Warehouse::getAll());
        return $this->fetch("index");
    }

    /**
     * 采购单追踪号搜索
     * @param PurchaseTrack $track 追踪号
     * @date 2021/01/18
     * @author longli
     */
    private function search($track)
    {
        $this->searchModel($track, [
            'eq' => ['track_status'],
            'times' => ['recv_date'],
        ]);
        $subSel = ['order_status', 'producer_id', 'warehouse_id'];
        $pWhere = [];
        foreach($subSel as $f)
        {
            $text = $this->request->post($f, '', 'trim');
            if(empty($text) && !is_numeric($text)) continue;
            $pWhere[$f] = $text;
        }
        if($sn = $this->request->post('sn', '', 'trim'))
        {
            if($pTemp = Purchase::getBySn($sn))
            {
                $pWhere["purchase_id"] = $pTemp->purchase_id;
            }
            else
            {
                $track->where('track_num', $sn);
            }
        }
        if(!empty($pWhere))
        {
            $track->where("purchase_id", "IN", function($query)use($pWhere)
            {
                $query->table(Purchase::getTable())->where($pWhere)->field("purchase_id");
            });
        }
    }

    /**
     * 添加采购追踪号
     * @date 2021/03/18
     * @author longli
     */
    public function add()
    {
        $trackId = $this->request->get('track_id');
        if($track = PurchaseTrack::get($trackId))
        {
            $this->assign('track', $track);
            $skuList = [];
            foreach($track->info as $info)
                $skuList[] = "{$info->sku}:{$info->qty}";
            $this->assign('skuList', join("\n", $skuList));
        }
        $this->assign('express', ChannelExpress::getAll());
        return $this->fetch('add');
    }

    /**
     * 保存采购追踪号
     * @date 2021/03/18
     * @author longli
     */
    public function save()
    {
        // 普通验证
        $validate = \think\facade\Validate::make([
            'purchase_sn'  => 'require',
            'track_num'  => 'require',
            'express_id'  => 'require',
        ],[
            'purchase_sn.require' => '采购单号不能为空',
            'express_id.require' => '物流商必选',
            'track_num.require' => '追踪号不能为空',
        ]);
        $data = $this->request->post();
        if(!$validate->batch()->check($data)) $this->error(join(', ', $validate->getError()));
        $po = $this->request->post('purchase_sn', '', 'trim');
        if(!($purchase = Purchase::getBySn($po))) $this->error("采购单【{$po}】不存在");
        //if(!isset($data['track_id']) && $purchase->track->count()) $this->error("采购单【{$po}】追踪号已录过");
        if($purchase->getData('order_status') < Purchase::ORDER_STATUS_GENERATE)
            $this->error("采购单【{$po}】状态为【{$purchase->order_status}】不能录入追踪号");
        $info = [];
        if(!empty($data['package']))
        {
            $package = explode("\n", str_replace(['：', ' '], [':', ''], $data['package']));
            $skus = [];
            foreach($package as $s)
            {
                if(!\app\common\library\Tools::contains($s, ':'))
                    $this->error("【{$s}】格式有误，请检查");
                list($sku, $qty) = explode(":", $s);
                $skus[] = $sku;
                $info[] = compact('sku', 'qty');
            }
            if(($diff = $purchase->isHasSku($skus)) !== true)
                $this->error(sprintf("【%s】不属于采购单【%s】", join(', ', $diff), $po));
        }
        $data['pay_type'] = $purchase->logistics_price > 0 ? PurchaseTrack::PAY_TYPE_M : PurchaseTrack::PAY_TYPE_T;
        PurchaseService::getInstance()->addTrack($purchase, $data, $info)
            ? $this->success('操作成功')
            : $this->error('操作失败');
    }

    /**
     * 采购单追踪号详情
     * @date 2020/12/22
     * @author longli
     */
    public function info()
    {
        $trackId = $this->request->get("track_id");
        if(empty($trackId)) $this->error("非法请求");
        $track = PurchaseTrack::get($trackId);
        if(empty($track)) $this->error("采购单不存在");
        if(empty($track->track_info)) $this->error("暂无物流信息");
        $trackInfo = json_decode($track->track_info, true);
        $this->assign("trackInfo", $trackInfo);
        return $this->fetch("track_info");
    }

    /**
     * 上传追踪号
     * @date 2020/12/22
     * @author longli
     */
    public function upload()
    {
        $file = $this->request->request("path");
        if(empty($file)) $this->error("非法请求");
        $file = BaseService::getRootPath($file);
        $import = new \app\common\service\import\PurchaseTrack($file);
        try
        {
            $import->run();
            return apiResponse(\app\common\status\BaseStatus::CODE_NORMAL, [], '导入成功');
        }catch(\RuntimeException $e)
        {
            return apiResponse(\app\common\status\BaseStatus::CODE_FAULT, [], $e->getMessage());
        }
    }

    /**
     * 查看物流详情
     * @date 2021/03/15
     * @author longli
     */
    public function track()
    {
        $ids = $this->request->get('ids');
        if(empty($ids)) $this->error('非法请求');
        \think\Console::call('logistics', ["--type=purchase", "--ids={$ids}"]);
        $this->success('同步成功');
    }
}